package com.winz.cultureapp.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.util.Log;
import android.view.View;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.flyco.tablayout.medol.TabEntity;
import com.winz.cultureapp.R;
import com.winz.cultureapp.adapter.vp.MainContentVpAdapter;
import com.winz.cultureapp.base.BaseAppCompatActivity;
import com.winz.cultureapp.constants.Constants;
import com.winz.cultureapp.entity.AppUpdateBean;
import com.winz.cultureapp.entity.EventBusBean;
import com.winz.cultureapp.fragment.ActivityFragment;
import com.winz.cultureapp.fragment.HomeFragment;
import com.winz.cultureapp.fragment.MineFragment;
import com.winz.cultureapp.fragment.StadiumFragment;
import com.winz.cultureapp.http.OnResponeListener;
import com.winz.cultureapp.http.request.RequestFactory;
import com.winz.cultureapp.http.util.HttpUitls;
import com.winz.cultureapp.utils.JsonUtil;
import com.winz.cultureapp.utils.Logger;
import com.winz.cultureapp.utils.VserionNameUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 主界面
 */
public class IndexActivity extends BaseAppCompatActivity implements OnTabSelectListener, ViewPager.OnPageChangeListener {
    private static final int BIRTH_TIME = 0x000001;
    private static final String PERMISSION_WRITE_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
    private static final String PERMISSION_CAMERA = Manifest.permission.CAMERA;
    private static final int REQUEST_PERMISSION_CODE = 267;
    @BindView(R.id.vp_main)
    public ViewPager mVp_main;
    @BindView(R.id.tl_main)
    public CommonTabLayout mCtl_main;
    @BindView(R.id.view_header)
    public View header;

    private MainContentVpAdapter mAdapter;
    private List<Fragment> mList_fragment;

    // 底部导航
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private String[] mTitles;
    private int[] mIconUnselectIds = {R.drawable.icon_main_item1_nor,
            R.drawable.icon_main_item2_nor,
            R.drawable.icon_main_item3_nor,
            R.drawable.icon_main_item4_nor};
    private int[] mIconSelectIds = {R.drawable.icon_main_item1_sel,
            R.drawable.icon_main_item2_sel,
            R.drawable.icon_main_item3_sel,
            R.drawable.icon_main_item4_sel};

    @Override
    protected int contentView() {
        setBackExit(true);
        return R.layout.activity_index;
    }

    @Override
    protected void initViews() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            setStatusBar(getResources().getColor(R.color.base_color));
        } else {
            header.setVisibility(View.GONE);
        }

        mList_fragment = new ArrayList<>();


        HomeFragment home = HomeFragment.getInstance();
        ActivityFragment activity = ActivityFragment.getInstance();
        StadiumFragment stadium = StadiumFragment.getInstance();
        MineFragment mine = MineFragment.getInstance();

        mList_fragment.add(home);
        mList_fragment.add(activity);
        mList_fragment.add(stadium);
        mList_fragment.add(mine);


        /**
         * tab初始化
         */
        mTitles = new String[mList_fragment.size()];
        mTitles[0] = getString(R.string.index_bottom_tab1);
        mTitles[1] = getString(R.string.index_bottom_tab2);
        mTitles[2] = getString(R.string.index_bottom_tab3);
        mTitles[3] = getString(R.string.index_bottom_tab4);


        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }

        EventBus.getDefault().register(this);

        //检查是否获得写入权限，未获得则向用户请求
        if (ActivityCompat.checkSelfPermission(this,PERMISSION_CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //未获得，向用户请求
            Log.d("Register", "无读写权限，开始请求权限。");
            ActivityCompat.requestPermissions(this, new String[]
                    {PERMISSION_CAMERA,PERMISSION_WRITE_STORAGE}, REQUEST_PERMISSION_CODE);
        } else {
            Log.d("Register", "有读写权限，准备启动相机。");

        }


    }

    @Override
    protected void initEvents() {

        mCtl_main.setTabData(mTabEntities, R.layout.layout_tab_custom);
        mCtl_main.setOnTabSelectListener(this);

        mAdapter = new MainContentVpAdapter(getSupportFragmentManager(), mList_fragment);
        mVp_main.setAdapter(mAdapter);
        mVp_main.setOffscreenPageLimit(4);
        mVp_main.addOnPageChangeListener(this);

    }

    @Override
    public void onTabSelect(int position) {
        mVp_main.setCurrentItem(position);
    }

    @Override
    public void onTabReselect(int position) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        mCtl_main.setCurrentTab(position);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (position == 3) {
                setStatusBar(Color.WHITE);
                header.setVisibility(View.GONE);
            } else {
                setStatusBar(getResources().getColor(R.color.base_color));
                header.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    @Subscribe
    public void messageEventBus(EventBusBean<String> event){
        if (event.type == 2){
            switch (event.action){
                case 20: // 文体活动
//                    mCtl_main.setCurrentTab(1);
                    mVp_main.setCurrentItem(1);
                    break;
                case 21: // 场馆预定
//                    mCtl_main.setCurrentTab(2);
                    mVp_main.setCurrentItem(2);
                    break;
                case 22: // 我的
//                    mCtl_main.setCurrentTab(3);
                    mVp_main.setCurrentItem(3);
                    break;
                case 23: // 登录
                    startActivity(LoginActivity.class,false);
                    break;
            }
        }

    }

    @Override
    public void update_version() {
        HttpUitls.onGet("app_update", RequestFactory.getInstance().app_update(VserionNameUtil.getVersionCode(this)+"","android"),new OnResponeListener<AppUpdateBean>() {
            @Override
            public void onSuccess(AppUpdateBean appUpdateBean) {
                Logger.d("app_update==>>", JsonUtil.getJsonFromObj(appUpdateBean));
                if (appUpdateBean.code == 0) {
                    if (appUpdateBean.code == 0){
                        //有最新版本，并返回下载url
                        String appUrl = appUpdateBean.data.appUpdateUrl;
                        if (appUrl != null && appUrl.length() > 0) {

                            showVersionDialog(appUpdateBean.data.appName,appUrl); //弹出是否更新对话框
                        }
                    }
                }
            }

            @Override
            public void onFailed(String error) {

            }
        });


    }

    protected void showVersionDialog(final String appName, final String appUrl) {
        AlertDialog.Builder versionDialog = new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT);
        versionDialog.setMessage("有新版本，是否升级？");
        versionDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
//                DownLoadApk.download(context,appUrl,appName,appName);

                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(Constants.URL.UPDATE);
                intent.setData(content_url);
                startActivity(intent);

                dialog.dismiss();


            }
        });
        versionDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        if (versionDialog != null) {
            versionDialog.show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 返回用户是否允许权限的结果，并处理
     */
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResult) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResult);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResult.length > 0 && grantResult[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户允许
                Logger.i("Register", "用户已允许权限，准备启动相机。");

            } else {
                //用户拒绝
                Logger.i("Register", "用户已拒绝权限，程序终止。");
                showMsg("您拒绝本应用使用相机，请在设置权限中允许使用相机功能！！！！");
            }
        }
    }
}
